<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input
                    v-model="model.billNo"
                    placeholder="请输入单据编号"
                    disabled
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicationId">
                  <select-user-by-dep
                    :multi="false"
                    v-model="model.applicationId"
                    disabled></select-user-by-dep>
                  <!-- <select-person-input :disabled="formDisabled" v-model="model.applicationId" @back="selectEmployee" /> -->
                  <!-- <select-person-input :disabled="formDisabled" v-model="model.employeeId" style="display:none" /> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart
                    :disabled="formDisabled"
                    v-model="model.applicant"
                    placeholder="请选择申请单位"
                    disabled
                  />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicationDeptId">
                  <j-select-depart :disabled="formDisabled" v-model="model.applicationDeptId" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="编制人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="staffingQuantity"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.staffingQuantity"
                    placeholder="请输入编制人数"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="实际人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="practicalQuantity"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.practicalQuantity"
                    placeholder="请输入实际人数"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="所需人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="requireQuantity"
                >
                  <a-input-number
                    :max="99999999"
                    :min="0"
                    v-model="model.requireQuantity"
                    placeholder="请输入所需人数"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="增岗事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="requireReason">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.requireReason" dictCode="require_reason" placeholder="请选择增岗事由" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    :disabled="formDisabled"
                    v-model="model.remark"
                    rows="4"
                    placeholder="请输入备注"
                    :max-length="500"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="岗位明细">
            <a-row>
              <a-col :span="24">
                <div style="margin-bottom: 6px; margin-top: 6px">
                  <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :loading="loading"
                  :columns="columns"
                  :pagination="false"
                  :data-source="model.itemList"
                  :scroll="{ x: true }"
                >
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleEdit(record)"
                      />
                      <a-divider type="vertical" />
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a-button class="ruleButton" :ghost="true" type="primary" icon="delete" />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments"></j-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <erp-hr-post-requirement-item-modal ref="itemList" @ok="modalFormOk"></erp-hr-post-requirement-item-modal>
      <process-config-modal ref="processConfig" @ok="handleSuccess" @close="handleClose"></process-config-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpHrPostRequirementBillFormPrint v-if="formBpm" class="print_style" id="hrpostContent" :formData="model" :formDataHistory="formData"></ErpHrPostRequirementBillFormPrint>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import ErpHrPostRequirementItemModal from './ErpHrPostRequirementItemModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ProcessConfigModal from '@/views/scy/components/ProcessConfigModal'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpHrPostRequirementBillFormPrint from './ErpHrPostRequirementBillFormPrint' // 打印组件
export default {
  name: 'ErpHrPostRequirementBillForm',
  components: {
    ProcessConfigModal,
    SelectUserByDep,
    SelectTeamInput,
    SelectCustomerInput,
    SelectProjectInput,
    ErpHrPostRequirementItemModal,
    CommonFlowList,
    ErpHrPostRequirementBillFormPrint
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      activeKey: ['1', '2', '3'],
      model: {
        itemList: []
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        bpmBizTitle: [
              { required: true, message: '请输入流程标题!' }
          ],
        applicationId: [
            { required: true, message: '请选择申请人!' }
        ],
        teamId: [
            { required: true, message: '请选择申请团队!' }
        ],
        staffingQuantity: [
            { required: true, message: '请输入编制人数!' },
            { pattern: /^[0-9]*[1-9][0-9]*|0$/, message: '请输入正整数!' }
        ],
        practicalQuantity: [
            { required: true, message: '请输入实际人数!' },
            { pattern: /^[0-9]*[1-9][0-9]*|0$/, message: '请输入正整数!' }
        ],
        requireQuantity: [
          { required: true, message: '请输入所需人数!' },
          { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
        ]
      },
      url: {
        startProcess: '/api/erpmng/act/process/extActProcess/startMutilProcess',
        getBillNo: '/api/erp/hr/post/erpHrPostRequirementBill/getBillNo',
        add: '/api/erp/hr/post/erpHrPostRequirementBill/add',
        edit: '/api/erp/hr/post/erpHrPostRequirementBill/edit',
        queryById: '/api/erp/hr/post/erpHrPostRequirementBill/queryById',
        queryEmployeeById: '/api/erp/files/employee/erpEmployeeFile/queryPageById'
      },
      loading: false,
      dictOptions: {},
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '岗位序列',
          align: 'center',
          dataIndex: 'positionCategory',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['positionCategory'], text + '')
            }
          }
        },
        {
          title: '岗位名称',
          align: 'center',
          dataIndex: 'postId',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['postId'], text + '')
            }
          }
        },
        {
          title: '工作地点',
          align: 'center',
          dataIndex: 'workAddress'
        },
        {
          title: '所需人数',
          align: 'center',
          dataIndex: 'requireQuantity'
        },
        {
          title: '学历要求',
          align: 'center',
          dataIndex: 'educationalRequirements',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['educationalRequirements'], text + '')
            }
          }
        },
        {
          title: '性别要求',
          align: 'center',
          dataIndex: 'sexRequirements',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['sexRequirements'], text + '')
            }
          }
        },
        {
          title: '专业要求',
          align: 'center',
          dataIndex: 'professionalRequirement',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['professionalRequirement'], text + '')
            }
          }
        },
        {
          title: '工作经验',
          align: 'center',
          dataIndex: 'workExperience',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['workExperience'], text + '')
            }
          }
        },
        {
          title: '薪资区间（元）',
          align: 'center',
          dataIndex: 'salarySection'
        },
        {
          title: '期待到岗时间',
          align: 'center',
          dataIndex: 'expectationTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      // 代码生成后需手动设置流程编码
      flowCode: 'onl_erp_hr_post_requirement_bill',
      formUrl: 'erp/hr/post/modules/ErpHrPostRequirementBillForm',
      formUrlMobile: '/pages/synergy/erpHrPostRequirementBillList',
      processId: '1540228876863561729',
      beanName: 'erpHrPostRequirementBillServiceImpl'
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  watch: {
    activeKey(key) {
      this.$forceUpdate()
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
    // 加载数据字典信息
    this.initDictConfig()
    if (this.formDisabled) {
      this.columns.pop()
    }
  },
  methods: {
    // 获取编号
    getBillNo() {
      getAction(this.url.getBillNo, {}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$set(this.model, 'billNo', data)
          this.$set(this.model, 'bpmBizTitle', this.userInfo().orgCodeTxt + '-' + data);
        }
      })
    },
    ...mapGetters(['userInfo']),
    add() {
      this.$set(this.modelDefault, 'itemList', []);
      this.edit(this.modelDefault);
      this.getBillNo();
      this.model.applicationId = this.userInfo().empId;
      this.model.applyId = this.userInfo().employee.applyId;
      this.model.applicationDeptId = this.userInfo().deptId;
      this.model.applicationDeptId = this.userInfo().deptId;
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    edit(record) {
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
      // this.model.applicationDeptId = this.userInfo().deptId;
      this.visible = true
    },
    // 2022-08-15 申请人是本人，不再查询获得
    // selectEmployee(data){
    //   getAction(this.url.queryEmployeeById,{ id: data[0].id }).then(res => {
    //     console.log(res);
    //     if(res.success){
    //       let data=res.result.records[0];
    //       this.$set(this.model,'applicant',data.orgDepart);
    //       this.$set(this.model,'applicationDeptId',data.departmentId);
    //       this.$set(this.model,'teamId',data.teamId);
    //     }
    //   })
    // },
    // 加载数据字典信息
    initDictConfig() {
      initDictOptions('sys_position,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'postId', res.result)
        }
      })
      initDictOptions('position_category').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'positionCategory', res.result)
        }
      })
      initDictOptions('educational_requirements').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'educationalRequirements', res.result)
        }
      })
      initDictOptions('sex_requirements').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'sexRequirements', res.result)
        }
      })
      initDictOptions('professional_requirement').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'professionalRequirement', res.result)
        }
      })
      initDictOptions('work_experience').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'workExperience', res.result)
        }
      })
    },
    // 子表新增
    handleAdd() {
      this.$refs.itemList.add()
      this.$refs.itemList.title = '新增'
      this.$refs.itemList.disableSubmit = false
    },
    // 子表编辑
    handleEdit(record) {
      this.$refs.itemList.edit(record)
      this.$refs.itemList.title = '修改'
      this.$refs.itemList.disableSubmit = false
    },
    // 子表删除
    handleDelete(id) {
      for (let i = 0; i < this.model.itemList.length; i++) {
        if (this.model.itemList[i].id == id) {
          this.model.itemList.splice(i, 1)
        }
      }
      // 设置所需人数
      let requireQuantity = 0;
      if (this.model.itemList) {
        this.model.itemList.forEach(item => {
          if (item.requireQuantity) {
            requireQuantity += item.requireQuantity;
          }
        })
        this.$set(this.model, 'requireQuantity', requireQuantity)
      }
    },
    modalFormOk(data) {
      this.loading = true
      let flag = true
      // debugger;
      for (let i = 0; i < this.model.itemList.length; i++) {
        if (this.model.itemList[i].id == data.id) {
          this.model.itemList.splice(i, 1, data)
          flag = false
        }
      }
      if (flag) {
        this.model.itemList.push(data)
      }
      // 设置所需人数
      let requireQuantity = 0;
      if (this.model.itemList) {
        this.model.itemList.forEach(item => {
          if (item.requireQuantity) {
            requireQuantity += item.requireQuantity;
          }
        })
        this.$set(this.model, 'requireQuantity', requireQuantity)
      }

      this.loading = false
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    handleSuccess() {
      this.$emit('ok', 'refresh');
    },
    handleClose () {
      this.$emit('close');
    },
    // 发起流程
    startProcess: function (id) {
      // var that = this;
      let record = { id: id };
      this.$refs.processConfig.visible = true
      this.$refs.processConfig.formUrl = this.formUrl
      this.$refs.processConfig.formUrlMobile = this.formUrlMobile
      this.$refs.processConfig.flowCode = this.flowCode
      this.$refs.processConfig.edit(record, '', this.beanName);
      // var param = {
      //   flowCode: that.flowCode,
      //   id: id,
      //   formUrl: that.formUrl,
      //   formUrlMobile: that.formUrlMobile
      // }
      //   postAction(that.url.startProcess, param).then((res) => {
      //     if (res.success) {
      //       that.$message.success(res.message);
      //       that.$emit('ok');
      //     } else {
      //       that.$message.warning(res.message);
      //     }
      //   }).catch((e) => {
      //     this.$message.warning('不识别的请求!');
      //   });
    },
    // 保存草稿
    submitTempForm() {
      const that = this
      // 触发表单验证
      // that.confirmLoading = true
      let httpurl = ''
      let method = ''
      if (!this.model.id) {
        httpurl += this.url.add
        method = 'post'
      } else {
        httpurl += this.url.edit
        method = 'put'
      }
      httpAction(httpurl, this.model, method)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok', 'draft', this.model);
            that.$emit('unButtonDisable');
          } else {
            that.$message.warning(res.message)
            that.$emit('unButtonDisable');
          }
        })
        .finally(() => {
          // that.confirmLoading = false
        })
    },
    submitForm (type) {
        const that = this;
        if (type && type == 'draft') {
          this.submitTempForm()
          return false
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                let data = res.result;
                if (this.model.id) {
                  // that.$message.success(res.message)
                  this.startProcess(this.model.id);
                } else {
                  // that.$message.success(res.message)
                  this.startProcess(data);
                  this.model.id = data;
                }
              } else {
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch(() => {
              that.$emit('unButtonDisable');
            })
            .finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#hrpostContent',
          popTitle: '岗位申请表详情 · 禾美环保',
          endCallback() {

          }
        })
      }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
</style>
